package main

import (
	"bufio"
	"fmt"
	"log"
	"net"
)

func handleClient(conn net.Conn) {
	defer conn.Close()

	// 状态机状态
	state := 0x00
	// 数据包长度
	length := uint16(0)
	// 数据包
	var recvBuffer []byte
	// 游标
	cursor := uint16(0)
	reader := bufio.NewReader(conn)

	for {
		v, err := reader.ReadByte()
		if err != nil {
			_ = conn.Close()
			return
		}

		switch state {
		case 0x00: // 帧头 2bytes 0xA55A
			if v == 0xA5 {
				state = 0x01
				//初始化
				recvBuffer = nil
				cursor = 0
			} else {
				state = 0x00
			}

		case 0x01:
			if v == 0x5A {
				state = 0x02
			} else {
				state = 0x00
			}

		case 0x02: // 帧长度 1byte
			if v >= 0x0f {
				length = uint16(v)
				// 一次申请缓存，准备读数据
				recvBuffer = make([]byte, length-4)
				recvBuffer[0] = 0xA5
				recvBuffer[1] = 0x5A
				recvBuffer[2] = v
				state = 0x03
			} else {
				state = errState(ip, "长度检测", "帧长度错误，丢弃数据", []byte{v})
			}

		case 0x03: // 厂家编号 1byte
			recvBuffer[3] = v
			state = 0x04

		case 0x04: // 协议版本 1byte
			recvBuffer[4] = v
			state = 0x05

		case 0x05: // 帧类型 1byte
			recvBuffer[5] = v
			state = 0x06

		case 0x06: // 设备编号 4bytes
			recvBuffer[6+cursor] = v
			cursor++
			if cursor == 4 {
				// 恢复游标，待读取数据备用
				cursor = 0
				// 如果数据段为空则跳过
				if (length - 15) != 0 {
					state = 0x07
				} else {
					state = 0x08
				}
			}

		case 0x07: // 信息段 Nbytes
			recvBuffer[10+cursor] = v
			cursor++
			if cursor == (length - 15) {
				state = 0x08
			}

		case 0x08: // 校验和 1byte

		case 0x09: // 帧尾 4bytes 0xCC33C33C

		}

	}
}

func main() {
	// 设置服务器监听的地址和端口
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal("监听失败:", err)
	}
	defer listener.Close()

	fmt.Println("服务器启动，监听 8080 端口...")

	// 接受连接
	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("接受连接失败:", err)
			continue
		}

		// 为每个连接创建一个 goroutine 来处理
		go handleClient(conn)
	}
}
